import axios from 'axios';
import { ElMessage } from 'element-plus';
import Router from '@/router/index';

function handleRouter(path: string) {
  Router.push(path);
}

const HttpClient = axios.create({
  baseURL: import.meta.env.VITE_PROXY_PATH,
});

HttpClient.interceptors.request.use(
  (config) => {
    // headers 设置
    return config;
  },
  (error) => {
    ElMessage.error(error.message);
    return Promise.reject(error);
  },
);

HttpClient.interceptors.response.use(
  (response) => {
    const { status, data } = response;
    if (status === 200) {
      const { code, message } = data;
      if (code == 200) {
        return response;
      } else if (code == 401) {
        handleRouter('/login');
      } else {
        ElMessage.error(message);
      }
    } else {
      // 枚举
      let errMsg = '';
      switch (status) {
        case 401:
          errMsg = '请重新登录';
          break;
        case 403:
          errMsg = '无权限查看';
          break;
        default:
          errMsg = '请检查服务';
          break;
      }
      ElMessage.error(errMsg);
    }
    return response;
  },
  (error) => {
    ElMessage.error(error.message);
    return Promise.reject(error);
  },
);

export default HttpClient;
